package com.jpxx.netty.chaibao2;

import io.netty.bootstrap.Bootstrap;  
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;  
import io.netty.channel.ChannelInitializer;  
import io.netty.channel.ChannelOption;  
import io.netty.channel.ChannelPipeline;  
import io.netty.channel.EventLoopGroup;  
import io.netty.channel.nio.NioEventLoopGroup;  
import io.netty.channel.socket.SocketChannel;  
import io.netty.channel.socket.nio.NioSocketChannel;  
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;  
import io.netty.handler.codec.string.StringEncoder;  
  
public class Client {  
      
    static final String HOST = System.getProperty("host", "127.0.0.1");  
    static final int PORT = Integer.parseInt(System.getProperty("port", "8765"));  
    static final int SIZE = Integer.parseInt(System.getProperty("size", "256"));  
  
    public static void main(String[] args) throws Exception {  
  
        // Configure the client.  
        EventLoopGroup group = new NioEventLoopGroup();  
        try {  
            Bootstrap b = new Bootstrap();  
            b.group(group)  
             .channel(NioSocketChannel.class)  // 指定客户端模式
             .option(ChannelOption.TCP_NODELAY, true)  
             .handler(new ChannelInitializer<SocketChannel>() {  
                 @Override  
                 public void initChannel(SocketChannel sc) throws Exception {  
                	//定长FixedLengthFrameDecoder   5  五个长度
                	 sc.pipeline().addLast(new FixedLengthFrameDecoder(5));  
                     sc.pipeline().addLast(new StringDecoder());//字符集
                     
                     sc.pipeline().addLast(new ClientHandler());  
                 }  
             });  
  
            ChannelFuture cf1 = b.connect(HOST, PORT).sync();//连接服务端的地方
            //连接成功
            System.out.println(HOST+PORT+"连接上~~~~~~");
            
            cf1.channel().writeAndFlush(Unpooled.copiedBuffer("aaabbcccc".getBytes()));
          //不够五个可以空格补全，要不就不接受
            cf1.channel().writeAndFlush(Unpooled.copiedBuffer("dddef".getBytes()));//不足5个不发送
            cf1.channel().closeFuture().sync();  
        } finally {  
            group.shutdownGracefully();  
        }  
    }  
  
}  